import { ipcMain } from 'electron'
import { sqDelete, sqInsert, sqQuery, sqUpdate } from './index'

ipcMain.handle('today-list', async (event, data) => {
  return await sqQuery({
    sql: `
    SELECT t.*, p.name as projectName
    FROM time t
    LEFT JOIN project p ON t.projectId = p.id
    WHERE date = ?`,
    params: [data.date]
  })
})

ipcMain.handle('today-add', async (event, data) => {
  for (const item of data.list) {
    let searchResList = await sqQuery({
      sql: `
      SELECT *
      FROM time
      WHERE date = ? AND projectId = ?`,
      params: [item.date, item.projectId]
    })
    let searchRes = searchResList[0]
    if (searchRes) {
      let newItem = { ...searchRes, time: searchRes.time + item.time, content: searchRes.content + ',' + item.content }
      await sqUpdate({ table: 'time', data: newItem, condition: `id = ${searchRes.id}` })
    } else {
      await sqInsert({ table: 'time', data: item })
    }
  }
  return 'success'
})

ipcMain.handle('today-edit', async (event, data) => {
  let sqlData = {
    id: data.id,
    content: data.content,
    time: data.time,
    date: data.date,
    projectId: data.projectId
  }
  return await sqUpdate({ table: 'time', data: sqlData, condition: `id = ${sqlData.id}` })
})

ipcMain.handle('today-delete', async (event, data) => {
  return await sqDelete({
    table: "time",
    condition: `id = ${data.id}`
  })
})
